package com.example.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.User;
import com.example.exception.CustomLoginException;
import com.example.mapper.SysMenuMapper;
import com.example.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 重构 Spring Security 的查询用户的方式
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {

        try {
            // 查询用户信息
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getUserName, username);
            User user = userService.getOne(lambdaQueryWrapper);

            // 查询权限信息
            List<String> list = menuMapper.selectPermsByUserId(user.getId());

            // 返回
            return new LoginUser(user, list);
        } catch (Exception e) {
            throw new InternalAuthenticationServiceException("用户名或密码不正确.");
        }
    }
}
